<template>
  <div class="map-container">
    <!-- 顶部控制栏 -->
    <div class="control-panel">
      <div class="left-controls">
        <h2 class="text-2xl font-bold">非遗地区分布</h2>
        <el-select v-model="selectedYear" placeholder="选择年份" class="year-select">
          <el-option
            v-for="year in years"
            :key="year"
            :label="year + '年'"
            :value="year"
          />
        </el-select>
        <el-select v-model="selectedCategory" placeholder="选择类别" class="category-select">
          <el-option
            v-for="category in categories"
            :key="category"
            :label="category"
            :value="category"
          />
        </el-select>
      </div>
      <div class="right-controls">
        <el-button-group>
          <el-button :type="viewMode === 'map' ? 'primary' : 'default'" @click="viewMode = 'map'">
            <el-icon><Map /></el-icon>
            地图视图
          </el-button>
          <el-button :type="viewMode === 'list' ? 'primary' : 'default'" @click="viewMode = 'list'">
            <el-icon><List /></el-icon>
            列表视图
          </el-button>
        </el-button-group>
      </div>
    </div>

    <!-- 主要内容区域 -->
    <div class="main-content">
      <!-- 地图视图 -->
      <div v-show="viewMode === 'map'" class="map-view">
        <div ref="mapChart" class="map-chart"></div>
        <div class="map-legend">
          <div class="legend-title">非遗项目数量</div>
          <div class="legend-scale">
            <el-tag
              v-for="(color, index) in legendColors"
              :key="index"
              :style="{ backgroundColor: color, borderColor: color }"
              class="legend-tag"
            >
              {{ legendLabels[index] }}
            </el-tag>
          </div>
        </div>
      </div>

      <!-- 列表视图 -->
      <div v-show="viewMode === 'list'" class="list-view">
        <el-table :data="heritageData" style="width: 100%" height="600">
          <el-table-column prop="region" label="地区" width="120" />
          <el-table-column prop="count" label="项目数量" width="120">
            <template #default="{ row }">
              <el-tag :type="getTagType(row.count)" effect="dark">{{ row.count }}</el-tag>
            </template>
          </el-table-column>
          <el-table-column prop="categories" label="主要类别">
            <template #default="{ row }">
              <el-tag 
                v-for="cat in row.categories" 
                :key="cat"
                class="mx-1"
                size="small"
                effect="plain"
              >
                {{ cat }}
              </el-tag>
            </template>
          </el-table-column>
          <el-table-column label="操作" width="120">
            <template #default="{ row }">
              <el-button 
                type="primary" 
                link
                @click="showRegionDetail(row.region)"
              >
                查看详情
              </el-button>
            </template>
          </el-table-column>
        </el-table>
      </div>
    </div>

    <!-- 地区详情弹窗 -->
    <el-dialog
      v-model="dialogVisible"
      :title="selectedRegion + '非遗项目详情'"
      width="70%"
      class="heritage-dialog"
    >
      <div class="region-detail">
        <div class="detail-header">
          <el-row :gutter="20">
            <el-col :span="8">
              <el-card class="stat-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <el-icon><Collection /></el-icon>
                    <span>项目总数</span>
                  </div>
                </template>
                <div class="card-value">{{ regionDetail.totalCount }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <el-icon><Medal /></el-icon>
                    <span>国家级项目</span>
                  </div>
                </template>
                <div class="card-value">{{ regionDetail.nationalCount }}</div>
              </el-card>
            </el-col>
            <el-col :span="8">
              <el-card class="stat-card" shadow="hover">
                <template #header>
                  <div class="card-header">
                    <el-icon><Trophy /></el-icon>
                    <span>省级项目</span>
                  </div>
                </template>
                <div class="card-value">{{ regionDetail.provincialCount }}</div>
              </el-card>
            </el-col>
          </el-row>
        </div>
        
        <div class="detail-charts">
          <el-row :gutter="20">
            <el-col :span="12">
              <el-card class="chart-card" shadow="hover">
                <template #header>
                  <div class="chart-header">
                    <el-icon><PieChart /></el-icon>
                    <span>项目类别分布</span>
                  </div>
                </template>
                <div ref="categoryChart" class="category-chart"></div>
              </el-card>
            </el-col>
            <el-col :span="12">
              <el-card class="chart-card" shadow="hover">
                <template #header>
                  <div class="chart-header">
                    <el-icon><TrendCharts /></el-icon>
                    <span>近五年发展趋势</span>
                  </div>
                </template>
                <div ref="trendChart" class="trend-chart"></div>
              </el-card>
            </el-col>
          </el-row>
        </div>
      </div>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from 'vue';
import * as echarts from 'echarts';
import 'echarts/map/js/china';
import { 
  Map, 
  List, 
  Collection, 
  Medal, 
  Trophy, 
  PieChart, 
  TrendCharts 
} from '@element-plus/icons-vue';
import { ElMessage } from 'element-plus';

// 状态管理
const mapChart = ref(null);
const categoryChart = ref(null);
const trendChart = ref(null);
const viewMode = ref('map');
const selectedYear = ref(new Date().getFullYear());
const selectedCategory = ref('');
const dialogVisible = ref(false);
const selectedRegion = ref('');
const regionDetail = ref({
  totalCount: 0,
  nationalCount: 0,
  provincialCount: 0
});

// 数据
const years = [2020, 2021, 2022, 2023];
const categories = ['传统技艺', '传统美术', '传统音乐', '传统舞蹈', '传统戏剧', '传统医药'];
const legendColors = ['#f0f9eb', '#e1f3d8', '#c2e7b0', '#95de64', '#67c23a'];
const legendLabels = ['0-10', '11-30', '31-50', '51-100', '100+'];

// 模拟数据
const heritageData = ref([
  { region: '北京', count: 45, categories: ['传统技艺', '传统美术'] },
  { region: '上海', count: 38, categories: ['传统音乐', '传统舞蹈'] },
  { region: '广东', count: 62, categories: ['传统戏剧', '传统医药'] },
  // 更多数据...
]);

// 方法
const initMap = () => {
  const chart = echarts.init(mapChart.value);
  const option = {
    title: {
      text: '非遗项目分布',
      left: 'center',
      top: 20,
      textStyle: {
        color: '#303133',
        fontSize: 20,
        fontWeight: 'bold'
      }
    },
    tooltip: {
      trigger: 'item',
      formatter: '{b}<br/>项目数量：{c}',
      backgroundColor: 'rgba(255, 255, 255, 0.9)',
      borderColor: '#dcdfe6',
      textStyle: {
        color: '#303133'
      }
    },
    visualMap: {
      min: 0,
      max: 100,
      left: 'left',
      top: 'bottom',
      text: ['高', '低'],
      calculable: true,
      inRange: {
        color: legendColors
      },
      textStyle: {
        color: '#606266'
      }
    },
    series: [
      {
        name: '非遗项目数量',
        type: 'map',
        map: 'china',
        roam: true,
        emphasis: {
          label: {
            show: true,
            color: '#303133'
          },
          itemStyle: {
            areaColor: '#67c23a'
          }
        },
        data: heritageData.value.map(item => ({
          name: item.region,
          value: item.count
        }))
      }
    ]
  };
  chart.setOption(option);
  
  chart.on('click', (params) => {
    showRegionDetail(params.name);
  });
};

const initCategoryChart = () => {
  const chart = echarts.init(categoryChart.value);
  const option = {
    tooltip: {
      trigger: 'item',
      formatter: '{b}: {c} ({d}%)'
    },
    legend: {
      orient: 'vertical',
      left: 'left',
      textStyle: {
        color: '#606266'
      }
    },
    series: [
      {
        type: 'pie',
        radius: '50%',
        data: [
          { value: 35, name: '传统技艺' },
          { value: 25, name: '传统美术' },
          { value: 20, name: '传统音乐' },
          { value: 15, name: '传统舞蹈' },
          { value: 10, name: '传统戏剧' },
          { value: 5, name: '传统医药' }
        ],
        emphasis: {
          itemStyle: {
            shadowBlur: 10,
            shadowOffsetX: 0,
            shadowColor: 'rgba(0, 0, 0, 0.5)'
          }
        },
        label: {
          color: '#606266'
        }
      }
    ]
  };
  chart.setOption(option);
};

const initTrendChart = () => {
  const chart = echarts.init(trendChart.value);
  const option = {
    tooltip: {
      trigger: 'axis'
    },
    xAxis: {
      type: 'category',
      data: ['2019', '2020', '2021', '2022', '2023'],
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266'
      }
    },
    yAxis: {
      type: 'value',
      axisLine: {
        lineStyle: {
          color: '#dcdfe6'
        }
      },
      axisLabel: {
        color: '#606266'
      },
      splitLine: {
        lineStyle: {
          color: '#ebeef5'
        }
      }
    },
    series: [
      {
        data: [30, 35, 40, 45, 50],
        type: 'line',
        smooth: true,
        symbol: 'circle',
        symbolSize: 8,
        itemStyle: {
          color: '#409eff'
        },
        lineStyle: {
          color: '#409eff',
          width: 3
        },
        areaStyle: {
          color: {
            type: 'linear',
            x: 0,
            y: 0,
            x2: 0,
            y2: 1,
            colorStops: [{
              offset: 0,
              color: 'rgba(64,158,255,0.3)'
            }, {
              offset: 1,
              color: 'rgba(64,158,255,0.1)'
            }]
          }
        }
      }
    ]
  };
  chart.setOption(option);
};

const showRegionDetail = (region) => {
  selectedRegion.value = region;
  dialogVisible.value = true;
  regionDetail.value = {
    totalCount: 45,
    nationalCount: 15,
    provincialCount: 30
  };
  
  setTimeout(() => {
    initCategoryChart();
    initTrendChart();
  }, 100);
};

const getTagType = (count) => {
  if (count > 50) return 'danger';
  if (count > 30) return 'warning';
  if (count > 10) return 'success';
  return 'info';
};

// 监听视图模式变化
watch(viewMode, (newMode) => {
  if (newMode === 'map') {
    setTimeout(initMap, 100);
  }
});

// 监听筛选条件变化
watch([selectedYear, selectedCategory], () => {
  ElMessage.success('数据已更新');
  if (viewMode.value === 'map') {
    setTimeout(initMap, 100);
  }
});

onMounted(() => {
  initMap();
  
  window.addEventListener('resize', () => {
    const mapChartInstance = echarts.getInstanceByDom(mapChart.value);
    if (mapChartInstance) {
      mapChartInstance.resize();
    }
  });
});
</script>

<style scoped>
.map-container {
  @apply min-h-screen bg-gray-50;
}

.control-panel {
  @apply bg-white shadow-sm p-4 flex justify-between items-center;
}

.left-controls {
  @apply flex items-center gap-4;
}

.year-select,
.category-select {
  @apply w-40;
}

.main-content {
  @apply p-4;
}

.map-view {
  @apply relative bg-white rounded-lg shadow-md p-4;
}

.map-chart {
  @apply h-[600px] w-full;
}

.map-legend {
  @apply absolute bottom-4 right-4 bg-white p-4 rounded-lg shadow-md;
}

.legend-title {
  @apply text-sm font-medium mb-2 text-gray-700;
}

.legend-scale {
  @apply flex flex-col gap-2;
}

.legend-tag {
  @apply text-gray-700 border-none;
}

.list-view {
  @apply bg-white rounded-lg shadow-md p-4;
}

.region-detail {
  @apply space-y-6;
}

.detail-header {
  @apply mb-6;
}

.stat-card {
  @apply text-center transition-all duration-300;
}

.card-header {
  @apply flex items-center justify-center gap-2 text-gray-600;
}

.card-value {
  @apply text-2xl font-bold text-primary-500 mt-2;
}

.chart-card {
  @apply h-full;
}

.chart-header {
  @apply flex items-center gap-2 text-gray-700;
}

.category-chart,
.trend-chart {
  @apply h-[300px];
}

:deep(.el-table) {
  @apply rounded-lg overflow-hidden;
}

:deep(.el-tag) {
  @apply mx-1;
}

:deep(.el-dialog) {
  @apply rounded-lg;
}

:deep(.el-dialog__header) {
  @apply border-b pb-4;
}

:deep(.el-card__header) {
  @apply border-b bg-gray-50;
}

:deep(.el-button-group) {
  @apply shadow-sm;
}

:deep(.el-select) {
  @apply shadow-sm;
}

:deep(.el-input) {
  @apply shadow-sm;
}
</style> 